import * as THREE from 'three';

/**
 * cube加载器
 * @param {String} path 图片存储路径 
 * @param {Array} array 图片名称
 */
export function cubeTextureLoader(path, array) {

	return new Promise((resolve, reject) => {
		let loader = new THREE.CubeTextureLoader();
		loader.setPath(path);
		loader.load(array, res => {
			resolve(res);
		});
		// loader.manager.onLoad = function(res) {
		// 	console.log('onLoad:', res)
		// }
		// loader.manager.onProgress = function(res) {
		// 	console.log('onProgress:', res)
		// }
		// loader.manager.onStart = function(res) {
		// 	console.log('onStart:', res)
		// }
		loader.manager.onError = function(res) {
			console.error('loader onError:', res)
			reject(res);
		}
	})

}
/**
 * 通过方向距离获取一个新的坐标点 https://www.thinbug.com/q/29183132
 * @param {Vector3} start 起点
 * @param {Vector3} direction 方向
 * @param {Number} distance 距离
 */
export function getPosByDirection(start, direction, distance) {
	var newPos = new THREE.Vector3();
	newPos.addVectors(start, direction.multiplyScalar(distance));
	return newPos;
}

/**
 * 创建一个图片元素
 * @param {string} path 图片路径
 * @param {Vector3} pos 位置
 * @param {Vector3} scale 缩放比例
 */
export function createSprite(path, pos, scale = new THREE.Vector3(1, 1, 1)) {
	let texture = new THREE.TextureLoader().load(path);
	let spriteMaterial = new THREE.SpriteMaterial({
		map: texture,
		color: 0xffffff,
		transparent: true
	});
	let sprite = new THREE.Sprite(spriteMaterial);
	sprite.scale.set(scale.x, scale.y, scale.z);
	sprite.position.copy(pos);
	return sprite;
}

/**
 * 获取相交元素返回第一个元素
 * @param {Number} x 屏幕坐标 (**归一化**)
 * @param {Number} y 屏幕坐标 (**归一化**)
 * @param {Object | Array} objs 审查元素
 * @param {Object} camera 摄像机
 */
export function getIntersects(x, y, objs, camera, scene) {
	let raycaster = new THREE.Raycaster();
	let mouseVector = new THREE.Vector2(x, y);
	raycaster.setFromCamera(mouseVector, camera);
	let intersects = Array.isArray(objs) ? raycaster.intersectObjects(objs) : raycaster.intersectObject(objs);
	// console.log('raycaster:',intersects,objs);
	if (intersects.length > 0)
		return intersects[0].object;
	return null;
}
